import { ElMessage } from 'element-plus';
import { AxiosError, AxiosResponse } from 'axios';
import { BeautyError } from '../beauty-error';
// 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
// 500表示服务器错误
export const responseSuccessInterceptor = (response: AxiosResponse<any>) => {
  if (response.status === 200) {
    if (response.data?.status === 500) {
      throw new BeautyError(response.data.errorCode, response.data.message);
    }
    if (response.data.response instanceof Array) {
      response.data = response.data.response;
    } else {
      response.data = response.data.response;
    }
  }
  return response;
};
// 401表示未登录
export const responseErrorInterceptor = (response: AxiosError<any>) => {
  if (response.response.status === 401) {
    ElMessage.warning('请先登录');
    location.href = '/';
  }
  return Promise.reject(
    new BeautyError(
      response.response.status,
      response.response.data?.errorMsg || response,
    ),
  );
};
